package com.jmpt.fangbohui.wecomm;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import cn.jpush.android.api.JPushInterface;

import com.google.gson.Gson;
import com.jmpt.fangbohui.Constants;
import com.jmpt.fangbohui.R;
import com.jmpt.fangbohui.ui.MainActivity;
import com.jmpt.fangbohui.utils.DebugLog;
import com.jmpt.fangbohui.utils.ToastHelper;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class WelComeActivity extends Activity{
	private String desc;
	private String downloadUrl;
	private PackageManager pm;
	private int currentCode;
	private static final int NEWVERSON = 1;
	private static final int LOADMAIN = 2;
	
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case NEWVERSON:
				AlertDialog.Builder dialog = new AlertDialog.Builder(WelComeActivity.this);
				dialog.setOnCancelListener(new OnCancelListener() {
					
					@Override
					public void onCancel(DialogInterface dialog) {
						// TODO Auto-generated method stub
						loadMain();
					}
				})
					  .setTitle("提醒")
				      .setMessage(desc)
				      .setNegativeButton("下次再说", new OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							//进入主界面
							loadMain();
							
						}
					})
				      .setPositiveButton("下载更新", new OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// 下载更新
							System.out.println("download:" + downloadUrl);
							download(downloadUrl);
							
						}

						
					});
				dialog.show();
				     
					  
				
				
				break;
			case LOADMAIN:
				  loadMain();
				 break;
			default:
				break;
			}
			
		};
	};
	private TextView tv_download;
	
	private void download(String downloadUrl) {
		// TODO Auto-generated method stub
		//下载本地sdcard
		tv_download.setVisibility(View.VISIBLE);
		HttpUtils utils = new HttpUtils();
		utils.download(downloadUrl, "/sdcard/fangbohui.apk", new RequestCallBack<File>() {
			
			@Override
			public void onSuccess(ResponseInfo<File> arg0) {
				tv_download.setVisibility(View.GONE);
				//下载成功
				//安装
				/*
				 *  <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:scheme="content" />
                <data android:scheme="file" />
                <data android:mimeType="application/vnd.android.package-archive" />
				 */
				Intent intent = new Intent();
				intent.setAction("android.intent.action.VIEW");
				intent.addCategory("android.intent.category.DEFAULT");
				//intent.setType("application/vnd.android.package-archive");
				intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "fangbohui.apk")),"application/vnd.android.package-archive");
				startActivityForResult(intent,0);
				
			}
			
			@Override
			public void onFailure(HttpException arg0, String arg1) {
				// TODO Auto-generated method stub
				System.out.println(arg0);
				tv_download.setVisibility(View.GONE);
				Toast.makeText(getApplicationContext(), "下载失败", 1).show();
				loadMain();
			}
			@Override
			public void onLoading(long total, long current, boolean isUploading) {
				super.onLoading(total, current, isUploading);
				tv_download.setText("当前进度："+(current/total)+"%");
			}
		});
	}
	
	public void loadMain(){
		
		Intent intent = new Intent(this,MainActivity.class);
		startActivity(intent);
		finish();//关闭当前界面
	}

	/**
     * Called when the activity is first created.
     */

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.activity_wecomm);
        initView();
        initData();
        //检查更新
        checkVersion();
        

//        new Handler().postDelayed(new Runnable() {
//            public void run() {
//                /* Create an Intent that will start the Main WordPress Activity. */
//                Intent mainIntent = new Intent(WelComeActivity.this, com.jmpt.fangbohui.ui.MainActivity.class);
//                WelComeActivity.this.startActivity(mainIntent);
//                WelComeActivity.this.finish();
//            }
//        }, 1900); //2900 for release
        
    }
    
	private void initView() {
		tv_download = (TextView) findViewById(R.id.tv_download);
	}

	private void initData() {
		try {

			pm = getPackageManager();
			PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);

			String versionName = packageInfo.versionName;
//			tv_versionname.setText(versionName);
			//获取当前的版本
			currentCode = packageInfo.versionCode;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			// can not reach 不可能发生
		}

	}
    
	/**
	 * 读取服务器数据，检测版本信息
	 */

	private void checkVersion() {
		
		HttpUtils utils = new HttpUtils();
		utils.send(HttpMethod.POST, Constants.URL.CHECK_VERSION, new RequestCallBack<String>()
		{
			@Override
			public void onFailure(HttpException arg0, String arg1)
			{
				ToastHelper.ShowToast("当前网络状态不良，无法检测最新版本", WelComeActivity.this);
				loadMain();
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0)
			{
				parserVersionResult(arg0.result);
			}
		});

	}
	
	private void parserVersionResult(String result) {
		DebugLog.i(result);
		Message msg = Message.obtain();//获取到缓存的消息
		long starttime = System.currentTimeMillis();
		try {
			Gson gson  = new Gson();
			VersionBean bean = gson.fromJson(result, VersionBean.class);
			
			//服务器的版本
			int serverCode = bean.retval.versionCode;
			desc = bean.retval.remarks;
			downloadUrl = bean.retval.url;
			
			if (serverCode > currentCode){//有新版本
				msg.what = NEWVERSON;
			} else { //版本一致
				msg.what = LOADMAIN;
			}
			
		} finally{
			long endtime = System.currentTimeMillis();
			if (endtime - starttime < 2000) {
				SystemClock.sleep(2000 - (endtime - starttime));
			} 
			handler.sendMessage(msg);
		}
	}
	public class VersionBean{
		public String done;
		public String msg;
		public Retval retval;
		public class Retval{
			public String remarks;
			public String url;
			public int versionCode;
			public String versionName;
		}
	}

	@Override
    protected void onResume() {
    	super.onRestart();
    	JPushInterface.onResume(this);
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
    }
}
